<?php

namespace app\api\controller;


class Order extends Base
{
    public function pre()
    {
        $user_id = $this->getuser();
        $goods_list = i("goods_list", "购物数据不能为空", "list");
        $type = i("type", "");
        $order_type = config('order_type');
        if (!array_key_exists($type, $order_type)) {
            e("订单类型不正确");
        }
        if (count($goods_list) == 0) {
            e("请输入购物数据");
        }
        $pre_order = [];
        $pre_order['user_id'] = $user_id;
        $pre_order['params']=i("params","","array");
        $type = i("type", "");

        $pre_order['type'] = $type;
        for ($i = 0; $i < count($goods_list); $i++) {
            $goods = model("goods")->where("id", $goods_list[$i]['id'])->find();
            $goods_list[$i]['price'] = $goods['price'];
            $goods_list[$i]['name'] = $goods['name'];
        }
        $pre_order['goods_list'] = $goods_list;
        $pre_order['no_pre'] = $order_type[$type]['no_pre'];
        $classname = "\\order\impl\\" . ucfirst($pre_order['type']);
        $order_object = new $classname();
        $pre_order = $order_object->make_pre($pre_order);

        $pre_token = uniqid();
        cache("pre_order_$pre_token", $pre_order, 60 * 86400);
        return s($pre_token);
    }

    public function get_pre()
    {
        $pre_token = input("pre_token");
        $order = cache("pre_order_$pre_token");
        if (empty($order)) {
            e("订单超时,请重新下单");
        }
        foreach ($order['goods_list'] as $key => $_goods) {
            $goods = model("goods")->where("id", $_goods['id'])->find()->toArray();
            $order['goods_list'][$key] = array_merge($order['goods_list'][$key], $goods);
        }
        return s($order);
    }


    public function make()
    {
        $order = $this->getorder();
        $classname = "\\order\impl\\" . ucfirst($order['type']);
        $order_object = new $classname();

        $order = $order_object->make($order);
        model("order")->allowField(true)->save($order);
        $goods_list = $order['goods_list'];
        for ($i = 0; $i < count($goods_list); $i++) {
            $goods = $goods_list[$i];
            $data = [];
            $data['goods_id'] = $goods['id'];
            $data['orderno'] = $order['orderno'];
            $data['price'] = $goods['price'];
            $data['number'] = $goods['buynumber'];
            model("orderGoodsList")->insert($data);
        }
        $price_list = $order['price_list'];
        for ($i = 0; $i < count($price_list); $i++) {
            $price = $price_list[$i];
            $data = [];
            $data['text'] = $price['text'];
            $data['orderno'] = $order['orderno'];
            $data['price'] = $price['price']/100;
            model("orderPriceList")->insert($data);
        }


        return s($order['orderno']);

    }

    private function getorder()
    {
        $pre_token = input("pre_token");
        $pre_order = cache("pre_order_$pre_token");
        $address = i("address", "请选择收件地址", "array");
        if (empty($address['addressee']) || empty($address['country']) || empty($address['tel'])) {
            e("请设置完整的收件地址");
        }
        if (empty($pre_order)) {
            e("订单超时,请重新下单");
        }
        $order = array_merge($address, $pre_order);
        $order['orderno'] = getorderno($pre_order['no_pre']);
        $order['datetime'] = now();
        $order['time'] = getMillisecond();
        $order['extend']=json_encode(empty($pre_order['extend'])?[]:$order['extend']);
        return $order;
    }

    public function pay()
    {
        $app = $this->getwxapp('pay');
        $user = $this->getuser(false);
        $orderno = input('orderno');
        $order = model('order')->where('orderno', $orderno)->find();

        if (empty($order)) {
            e("订单不存在");
        }
        if ($order['ispay'] != 0) {
            e("订单状态不允许支付");
        }
        $result = $app->order->unify([
            'body' => '支付',
            'out_trade_no' => $orderno,
            //'total_fee' => intval($order['totalprice']*100),
            'total_fee' => 1,
            'trade_type' => 'JSAPI',
            'openid' => $user['openid'],
        ]);
        if (empty($result['prepay_id'])) {
            e($result['err_code_des']);
        }
        $prepay_id = $result['prepay_id'];

        $jssdk = $app->jssdk;
        $config = $jssdk->sdkConfig($prepay_id);
        return s($config);
    }

    public function notify()
    {
        $app = $this->getwxapp("pay");
        $response = $app->handlePaidNotify(function ($message, $fail) {
            model("notify")->insert(['message'=>json_encode($message),"datetime"=>now()]);
            $orderno = $message['out_trade_no'];
            $order = model("order")->where("orderno", $orderno)->find();
            if (empty($order)) {
                return true;
            }
            if ($order['ispay'] != 0) {
                return true;
            }

            $type = $order['type'];

            $classname = "\\order\impl\\" . ucfirst($order['type']);
            $order_object = new $classname();
            $statue = $order_object->notify($order);

            $order_goods_lists = model("OrderGoodsList")->where("orderno",$orderno)->find();
            $num = $order_goods_lists["number"];
            $goods_id = $order_goods_lists["goods_id"];
            //cnumber
            $goods = model("goods")->where("id",$goods_id)->find();
            $user_id=$order['user_id'];
            $user=model("user")->where("id",$user_id)->find();
            if(!empty($user['group_code'])){
                $group=model("group")->where("code",$user['group_code'])->find();
                if(!empty($group)){
                    money($group['user_id'],$order['totalprice']*0.06,"订单:{$orderno}佣金返现");
                }

            }
            inventory($goods_id,-$num,"订单{$orderno}消耗");
            model("goods")->where("id",$goods_id)->update(['sales'=>$goods["sales"]+$num]);
            if($goods['inpack']!=0){
                $packsales=model("goods")->where("inpack",$goods['inpack'])->sum("sales");
                model("goods")->where("id",$goods_id)->update(['sales'=>$packsales]);
            }
            return true;
        });
        $response->send();
    }

}
